#!usr/bin/env python  
# -*- coding:utf-8 _*-
""" 
@author:robot
@file: report_base.py 
@version:
@time: 2022/03/18 
"""
import json
import time

from TapClientCore.T01_init_conf.path_conf import PathConf
from TapUtil.Tfeishu.feishu_webhook import FeiShuWebHook
from TapUtil.operatefile.use_json import read_json


class ReportBase(FeiShuWebHook):

    @staticmethod
    def time_dif(start, end):
        timestamp1 = time.strptime(start, '%Y-%m-%d %H:%M:%S')
        timestamp2 = time.strptime(end, '%Y-%m-%d %H:%M:%S')
        ti = time.gmtime(time.mktime(timestamp2) - time.mktime(timestamp1))
        return '%s天%s:%s:%s' % (str(ti.tm_mday - 1).zfill(2),
                                str(ti.tm_hour).zfill(2),
                                str(ti.tm_min).zfill(2),
                                str(ti.tm_sec).zfill(2))

    @staticmethod
    def analyse():
        """
        pytest 执行日志解析
        :param self:
        :return:
        """
        _result = {}
        _keys = "when"
        _outcome = "outcome"
        all_count = 0
        pass_count = 0
        err_count = 0
        skip_count = 0
        rerun_count = 0
        exec_count = 0
        with open(PathConf.PYTEST_RESULT_PATH, "r") as f:
            for oneline in f.readlines():
                dic_oneline = json.loads(oneline)
                if _keys in dic_oneline and dic_oneline[_keys] == "call":
                    all_count += 1
                    if dic_oneline[_outcome] == "passed":
                        pass_count += 1
                    if dic_oneline[_outcome] == "failed":
                        err_count += 1
                    if dic_oneline[_outcome] == "skipped":
                        skip_count += 1
                    if dic_oneline[_outcome] == "rerun":
                        rerun_count += 1
                if _keys in dic_oneline and dic_oneline[_keys] == "setup" and dic_oneline[_outcome] == "skipped":
                    all_count += 1
                    skip_count += 1
        try:
            exec_count = all_count - skip_count -rerun_count
            if err_count / exec_count <= 0.1:
                _result["color"] = "Green"
            elif err_count / exec_count <= 0.3:
                _result["color"] = "blue"
            elif err_count / exec_count <= 0.6:
                _result["color"] = "yellow"
            else:
                _result["color"] = "red"
        except:
            _result["color"] = "red"
        # 重跑案例不再算入其中
        _result["all_case"] = str(all_count - rerun_count)
        _result["pass_case"] = str(pass_count)
        _result["fail_case"] = str(err_count)
        _result["skip_case"] = str(skip_count)
        # from api.other_config import retime
        _result["rerun_case"] = str(rerun_count)
        return _result
